import * as api from '@/services/checkSchedule';
import {
  PlusOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import { DrawerForm, ProFormInstance } from '@ant-design/pro-form';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Popconfirm,
  Space,
  Tag,
} from 'antd';
import React, { useRef, useState } from 'react';
import { useModel } from 'umi';
import * as utils from '@/utils/utils';
import CheckTaskReportForm from '../CheckTask/CheckReportForm';
import EventReportForm from '../IdcApiEvent/ReportForm';
import CheckTaskStatusTag from '@/components/CheckTaskStatusTag';
import IdcApiEventStatusTag from '@/components/IdcApiEventStatusTag';
import CheckScheduleLogStatusTag from '@/components/CheckScheduleLogStatusTag';

type VpnServerFormProps = {
  visible: boolean;
  current: API.CheckSchedule | undefined;
  onCancel: () => void;
};

const VpnServerForm: React.FC<VpnServerFormProps> = (props) => {
  const { visible, onCancel,  current } = props;

  if (!visible) {
    return null;
  }

  const { hasRight } = useModel('useAuthModel');
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const [formCheckTaskReportVisible, setFormCheckTaskReportVisible] =useState<boolean>(false);
  const [currentTaskVer, setCurrentTaskVer] = useState<string | undefined>(undefined);
  const [formEventReportVisible, setFormEventReportVisible] =useState<boolean>(false);
  const [currentEventVer, setCurrentEventVer] = useState<string | undefined>(undefined);



  const handleRemoves = async (keys:any[]) => {
    const result = await api.removeLogs({keys});
    if (result && result.success) {
      actionRef?.current?.clearSelected();
      actionRef?.current?.reload();
    }
  };
  
  const logColumns: ProColumns<API.CheckScheduleLog>[] = [
    {
      title: '下发时间',
      dataIndex: 'createTime',
      width:240,
      render: (_, record) => {
        return <>
        <div><CheckScheduleLogStatusTag status={record.status} /><span style={{color:'#999'}}>P:{record.schedulePublishId}</span></div>
        <div><PlusOutlined /> {utils.formatDate(record.createTime)}</div>
        <div> {record.updateTime ? <><RedoOutlined /> {utils.formatDate(record.updateTime)}</> : ''}</div>
        </>
      },
    },
    {
      title: '执行信息',
      dataIndex: 'message',
    },
    {
      title: '执行结果',
      dataIndex: 'reports',
      width:500,
      render: (_, record) => {
        
          return <>
            {record.reports?.length > 0 ? <Tag color='error'><b>被墙：{record.reports?.length} </b></Tag> : ''}

            {record.tasks?.length > 0 ? record.tasks?.map((val) => { return <div>
              <a
                onClick={(e) => {
                  setFormCheckTaskReportVisible(true);
                  setCurrentTaskVer(val.id);
                }}
              >
                <Tag color='cyan' style={{width:50}}>检测</Tag><b>{val.id}</b> [{utils.formatDate(val.createTime)}
                ] <CheckTaskStatusTag status={val.status} />
              </a>
            </div>}) : ''}

          {record.events?.length > 0 ? record.events?.map((val) => { return <div>
            <a
              onClick={(e) => {
                setFormEventReportVisible(true);
                setCurrentEventVer(val.id);
              }}
            >
              <Tag color='blue'>更换IP</Tag><b>{val.id}</b> [{utils.formatDate(val.createTime)}
              ] <IdcApiEventStatusTag status={val.status} />
            </a>
          </div>}) : ''}


            </>
      },
    },
  ];

  return (
    <DrawerForm<API.CheckTask>
      open={visible}
      title={
        <>
          执行记录 <Tag color="blue">版本：{current?.id}</Tag>{' '}<Tag color="blue">名称：{current?.name}</Tag>
        </>
      }
      formRef={formRef}
      autoFocusFirstInput
      width={1200}
      // onFinish={handleFormSubmit}
      drawerProps={{
        // forceRender: true,
        // destroyOnClose: true,
        // closable: false,
        onClose: onCancel,
        maskClosable: false,
      }}
      submitter={{
        render: (props, defaultDoms) => {
          return [defaultDoms[0]];
        },
      }}
    >

      <ProTable<API.CheckScheduleLog>
        rowKey="id"
        actionRef={actionRef}
        options={{
          fullScreen: false,
          reload: true,
          setting: false,
          density: false,
        }}
        search={false}
        columns={logColumns}
        expandable={undefined}
        rowSelection={{
          defaultSelectedRowKeys: [],
          // onChange: (selectedRowKeys, selectedRows) => {
          //   setSelectIds(selectedRowKeys);
          // },
        }}
        tableAlertRender={({
          selectedRowKeys,
          selectedRows,
          onCleanSelected,
        }) => (
          <Space size={24}>
            <span>
              已选 {selectedRowKeys.length} 条记录
              <a style={{ marginLeft: 8 }} onClick={onCleanSelected}>
                取消
              </a>
            </span>
            

            <span>
              {hasRight('checkschedule_delete') ?
                  <Popconfirm
                    key="check_delete"
                    title="确定要删除吗?"
                    onConfirm={async () => {
                      await handleRemoves(selectedRowKeys);
                    }}
                  >
                    <a>删除</a>
                  </Popconfirm>
                : ''
              }
            </span>
          </Space>
        )}
        params={{
          scheduleId: current?.id
        }}
        request={api.logs}
        pagination={{
          defaultPageSize: 15,
          pageSizeOptions: [
            '15',
            '50',
            '100',
            '200',
            '300',
          ],
          hideOnSinglePage: false,
        }}
      />

      <CheckTaskReportForm
        visible={formCheckTaskReportVisible}
        ver={currentTaskVer}
        groupId={undefined}
        onCancel={() => {
          setFormCheckTaskReportVisible(false);
          setCurrentTaskVer(undefined);
        }}
        onCancelAndReload={() => {
          setFormCheckTaskReportVisible(false);
          setCurrentTaskVer(undefined);
          // actionRef.current?.reload();
        }}
      />
      <EventReportForm
        visible={formEventReportVisible}
        ver={currentEventVer}
        onCancel={() => {
          setFormEventReportVisible(false);
          setCurrentEventVer(undefined);
        }}
      />



    </DrawerForm>
  );
};

export default VpnServerForm;
